package com.ruoyi.common.utils;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class PrimaryKeyUtils {

    //代码同步，防止高并发
    private final static ReentrantLock lock;
    static{
        lock = new ReentrantLock();
    }

    public static String generateCode(String pre,String oldCode){
        Map<String, Object> map = new HashMap<String, Object>();

        Integer preLen = 3;
        Integer num = 14;
        Integer noLen = 6;

        Date curr = new Date();
        SimpleDateFormat formatter = null;

        switch (num) {
            case 4:
                formatter = new SimpleDateFormat("yyyy");
                break;
            case 6:
                formatter = new SimpleDateFormat("yyyyMM");
                break;
            case 8:
                formatter = new SimpleDateFormat("yyyyMMdd");
                break;
            case 12:
                formatter = new SimpleDateFormat("yyyyMMddHHmm");
                break;
            case 14:
                formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                break;

            default:
                break;
        }

        String currentDate = formatter.format(curr);

        map.put("pre", pre);
        map.put("preLen", preLen);
        map.put("num", num);
        map.put("noLen", noLen);
        map.put("currentDate", currentDate);

        lock.lock();

        String newCode = "";
        String newNo = "";

        try {

            if (StringUtils.isEmpty(oldCode)) {
                newNo = "1";
            } else {
                Integer maxNo = Integer.parseInt(oldCode.substring(oldCode.length() - noLen));
                newNo = String.valueOf(maxNo + 1);
            }

            int length = newNo.length();

            if(length > noLen){
                System.out.println("新流水号位数超限");
            }

            for (int i = 0; i < noLen - length; i++) {
                newNo = "0".concat(newNo);
            }

            newCode = pre + currentDate + newNo;

        } finally {
            lock.unlock();
        }

        System.out.println("生成的编码为："+newCode);
        return newCode;
    }

}
